package com.xjh.t.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjh.t.common.ActiverClientUser;
import com.xjh.t.common.ActiverUser;
import com.xjh.t.domain.ClientUser;
import com.xjh.t.domain.User;
import com.xjh.t.service.IClientUserService;
import com.xjh.t.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

public class ClientUserRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private IClientUserService userService;
    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        QueryWrapper<ClientUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ur_phone",authenticationToken.getPrincipal().toString());
        ClientUser user = userService.getOne(queryWrapper);
        if(null != user)
        {
            ActiverClientUser activerUser = new ActiverClientUser();
            activerUser.setUser(user);
            ByteSource credent = ByteSource.Util.bytes(user.getUrSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activerUser,user.getUrPwd(),credent,this.getName());
            return info;
        }
        return null;
    }
}
